package com.jstyle.jclifexd.activity;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Toast;

import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.ActivitvtAdapter;
import com.jstyle.jclifexd.model.Created;
import com.jstyle.jclifexd.model.Createddata;
import com.jstyle.jclifexd.model.QueryUserStatemsg;
import com.jstyle.jclifexd.utils.RxBus;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.StatusBarUtil;
import com.jstyle.jclifexd.utils.Utils;

import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 活动
 */
public class ActivitiesActivity extends BaseActivity {
    @BindView(R.id.activity_RecyclerView)
    RecyclerView activity_RecyclerView;
    ActivitvtAdapter activitvtiesAdapter;
    NotificationManager notificationManager;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activities);
        StatusBarUtil.setRootViewFitsSystemWindows(this, true);
        StatusBarUtil.setTranslucentStatus(this);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
        notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(1);
        ButterKnife.bind(this);
        activity_RecyclerView.setLayoutManager(new LinearLayoutManager(this));
        activitvtiesAdapter = new ActivitvtAdapter(this);
        activity_RecyclerView.setAdapter(activitvtiesAdapter);
        activitvtiesAdapter.setOnItemClickListener(new ActivitvtAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Createddata aa, int position) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (aa.getAvailably() == 0) {//已关闭
                    Toast.makeText(ActivitiesActivity.this, ActivitiesActivity.this.getResources().getString(R.string.closed), Toast.LENGTH_SHORT).show();
                } else {
                    if (Utils.checkNetWork(ActivitiesActivity.this)) {
                        switch (aa.getType()) {
                            case "pk"://团队pk
                                QueryUserState(aa);
                                break;
                            default://判断是否加入活动，已加入进入排名界面
                                if ((int) aa.getState() == 1) {
                                    Intent intent = new Intent(ActivitiesActivity.this, ActivityrankingActivity.class);
                                    intent.putExtra("activitiesActivity", aa);
                                    startActivity(intent);
                                } else {
                                    Intent intent = new Intent(ActivitiesActivity.this, DetailsActivity.class);
                                    intent.putExtra("Createddata", aa);
                                    startActivity(intent);
                                }
                                break;
                        }
                    } else {
                        showToast(ActivitiesActivity.this.getString(R.string.Network_not_availa));
                    }
                }

            }
        });
        Querydata();

        /**
         * 如果退出了活动当前界面需要刷新状态
         */
        RxBus.getInstance().toObservable(String.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String bleData) {
                if (null != bleData) {
                    if (bleData.equals("reload")) {
                        Querydata();
                    }
                }
            }
        });
    }

    private void QueryUserState(final Createddata aa) {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", NetWorkUtil.getUserId());
        NetWorkUtil.getInstance().getJstyleApi().getqueryUserState(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<QueryUserStatemsg>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(QueryUserStatemsg activitvtiesData) {
                if (activitvtiesData.getData().getTeamId() == 0) {
                    Intent intent = new Intent(ActivitiesActivity.this, TeamPKActivity.class);
                    intent.putExtra("activitiesActivity", aa);
                    startActivity(intent);
                } else {
                    //进入战队排名界面
                    Intent intent = new Intent(ActivitiesActivity.this, TeamperformanceActivity.class);
                    intent.putExtra("activitiesActivity", aa);
                    startActivity(intent);
                }


            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });

    }
    private Disposable queryDisposable;
    private void Querydata() {
        Map<String, Object> map = new HashMap<>();
        map.put("uid", NetWorkUtil.getUserId());//"uid" -> "111000036"
        NetWorkUtil.getInstance().getJstyleApi().queryAll(map).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Created>() {
            @Override
            public void onSubscribe(Disposable d) {
                queryDisposable=d;
            }

            @Override
            public void onNext(Created activitvtiesData) {
                activitvtiesAdapter.SetData(activitvtiesData.getData());
                LayoutAnimationController controller =
                        AnimationUtils.loadLayoutAnimation(activity_RecyclerView.getContext(),
                                R.anim.layout_animation_fall_down);
                activity_RecyclerView.setLayoutAnimation(controller);
                Objects.requireNonNull(activity_RecyclerView.getAdapter()).notifyDataSetChanged();
                activity_RecyclerView.scheduleLayoutAnimation();
            }

            @Override
            public void onError(Throwable e) {
                String msg = e.getMessage();
                if (e instanceof ConnectException) {
                    msg = getString(R.string.Network_not_availa);
                }
                ScreenUtils.showSetSuccessFul(activity_RecyclerView,msg);
            }

            @Override
            public void onComplete() {
            }
        });

    }

    @OnClick({R.id.iv_back, R.id.create_activities})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.create_activities:
                startActivity(CreateActivitiesoneActivity.class);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(queryDisposable);
    }
}
